﻿using DataManageSystem.Common;
using DataManageSystem.Data;
using DataManageSystem.Exceptions;
using DataManageSystem.Models;
using DataManageSystem.Models.Dto;
using DataManageSystem.Services;
using DataManageSystem.Utils;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using OfficeOpenXml;

namespace DataManageSystem.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly ApplicationDbContext _context;
        private readonly UserServices userService;
        private readonly IHttpContextAccessor httpContextAccessor;
        private readonly IConfiguration _config;

        public UserController(
            UserServices userService,
            IHttpContextAccessor httpContextAccessor,
            IConfiguration config,
            ApplicationDbContext context
        )
        {
            this.userService = userService;
            this.httpContextAccessor = httpContextAccessor;
            _config = config;
            _context = context;
        }

        /// <summary>
        /// 迁移人员数据到lims系统数据库
        /// </summary>
        /// <returns></returns>
        [HttpGet("migration")]
        public ObjectResult Migration()
        {
            var res = userService.Migration();
            return new ObjectResult(Result.Success(res));
        }

        [HttpGet("selectByPage")]
        public ObjectResult selectByPage(
            [FromQuery] int pageNum = 1,
            [FromQuery] int pageSize = 10,
            [FromQuery] string userName = "",
            [FromQuery] string name = ""
        )
        {
            var res = userService.selectByPage(pageNum, pageSize, userName, name);
            return new ObjectResult(res);
        }

        [HttpGet("selectByName")]
        public ObjectResult selectByName([FromQuery] string userName = "")
        {
            var res = userService.selectByName(userName);
            return new ObjectResult(res);
        }

        [HttpPost("add")]
        public ObjectResult add([FromBody] User user)
        {
            try
            {
                user.Avatar =
                    "http://139.196.170.188:9000/blacket/2bbf7f37-68fb-4805-8aab-01d63ac7bd6f.png";
                userService.add(user);
                return new ObjectResult(Result.Success("添加成功"));
            }
            catch (ServiceException ex)
            {
                // 处理自定义异常
                return new ObjectResult(Result.Error(ex.Message));
            }
            catch (Exception ex)
            {
                // 处理其他异常
                return new ObjectResult(Result.Error());
            }
        }

        [HttpPut("update")]
        public ObjectResult update([FromBody] UserDto userDto)
        {
            try
            {
                userService.update(userDto);
                return new ObjectResult(Result.Success("更新成功"));
            }
            catch (ServiceException ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
            catch (Exception ex)
            {
                return new ObjectResult(Result.Error(ex.Message));
            }
        }

        [HttpDelete("delete/{id}")]
        public ObjectResult delete(int id)
        {
            User currentUser = TokenUtils.GetCurrentUser(httpContextAccessor, userService, _config);
            if (currentUser == null || currentUser.Role == "用户" || currentUser.Id == id)
            {
                return new ObjectResult(Result.Error("没有权限删除该用户"));
            }
            else
            {
                try
                {
                    userService.delete(id);
                    return new ObjectResult(Result.Success("删除成功"));
                }
                catch (ServiceException ex)
                {
                    return new ObjectResult(Result.Error(ex.Message));
                }
                catch (Exception ex)
                {
                    return new ObjectResult(Result.Error(ex.Message));
                }
            }
        }

        /// <summary>
        /// 人员信息批量导入接口
        /// </summary>
        /// <returns></returns>
        [HttpPost("import")]
        public ObjectResult import(IFormFile file)
        {
            if (file == null || file.Length == 0)
            {
                return new ObjectResult(Result.Error("文件不能为空！"));
            }

            var users = new List<User>();

            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

            using (var stream = new MemoryStream())
            {
                file.CopyToAsync(stream);
                using (var package = new ExcelPackage(stream))
                {
                    var worksheet = package.Workbook.Worksheets[0]; // 读取第一个Sheet
                    int rowCount = worksheet.Dimension.Rows; // 获取行数

                    for (int row = 2; row <= rowCount; row++) // 跳过表头，从第2行开始
                    {
                        users.Add(
                            new User
                            {
                                Username = worksheet.Cells[row, 1].Text, //账户
                                Name = worksheet.Cells[row, 2].Text, //姓名
                            }
                        );
                    }
                }
            }

            if (!users.Any())
            {
                return new ObjectResult(Result.Error("Excel 文件为空或格式不正确！"));
            }

            var entityList = users
                .Select(d => new User
                {
                    Username = d.Username,
                    Password = "123456",
                    Name = d.Name,
                    Phone = "",
                    Email = "",
                    Address = "",
                    Avatar = "http://139.196.170.188:9000/blacket/2bbf7f37-68fb-4805-8aab-01d63ac7bd6f.png",
                    Role = "用户",
                })
                .ToList();

            _context.User.AddRange(entityList);
            _context.SaveChanges();

            return new ObjectResult(Result.Success("批量导入成功"));
        }
    }
}
